class LocalStorageManager {
  /**
   * 创建本地存储管理器
   * @param {string} [namespace=''] 命名空间
   * @param {'local'|'session'} [storageType='session'] 存储类型
   */
  constructor(namespace = '', storageType = 'session') {
    this.namespace = namespace.replace(/[^\w]/g, '_');
    this.storage = storageType === 'local' ? window.localStorage : window.sessionStorage;
  }

  // 前缀处理函数，规范化存储键名
  prefixKey(key) {
    return `${this.namespace}:${key}`.replace(/[:]+/g, ':');
  }

  // 设置数据
  setItem(key, value) {
    try {
      const serializedValue = this.serializer(value);
      const storageSize = new Blob([serializedValue]).size;
      
      // Check storage quota
      if (!this.checkStorageQuota(storageSize)) {
        throw new Error('Insufficient storage space');
      }

      this.storage.setItem(this.prefixKey(key), serializedValue);
    } catch (error) {
      console.error('Storage operation failed:', error);
      throw new Error(`StorageError: ${error.message}`);
    }
  }

  // 获取数据
  getItem(key) {
    try {
      const item = this.storage.getItem(this.prefixKey(key));
      return item ? this.deserializer(item) : null;
    } catch (error) {
      console.error('Error getting item:', error);
      return null;
    }
  }

  // 自定义序列化方法
  serializer(value) {
    try {
      const replacer = (key, val) => {
        if (val instanceof Map) return { __type: 'Map', value: [...val] };
        if (val instanceof Set) return { __type: 'Set', value: [...val] };
        return val;
      };
      return JSON.stringify(value, replacer);
    } catch (error) {
      throw new Error(`Serialization failed: ${error.message}`);
    }
  }

  // 自定义反序列化方法
  deserializer(value) {
    try {
      const reviver = (key, val) => {
        if (val?.__type === 'Map') return new Map(val.value);
        if (val?.__type === 'Set') return new Set(val.value);
        return val;
      };
      return JSON.parse(value, reviver);
    } catch (error) {
      throw new Error(`Deserialization failed: ${error.message}`);
    }
  }

  // 存储空间检查
  checkStorageQuota(requiredSize) {
    try {
      let totalSize = 0;
      for (let i = 0; i < this.storage.length; i++) {
        const key = this.storage.key(i);
        if (key && this.storage.getItem(key)) {
          totalSize += new Blob([this.storage.getItem(key)]).size;
        }
      }
      return totalSize + requiredSize < 4_194_304; // 4MB for sessionStorage
    } catch (error) {
      console.error('Storage quota check failed:', error);
      return false;
    }
  }

  // 删除数据
  removeItem(key) {
    this.storage.removeItem(this.prefixKey(key));
  }

  // 清空所有数据
  clear() {
    const keys = Object.keys(this.storage).filter((k) => k.startsWith(this.prefixKey('')));
    keys.forEach((key) => this.storage.removeItem(key));
  }

  // 检查是否包含某个key
  hasItem(key) {
    return Object.prototype.hasOwnProperty.call(this.storage, this.prefixKey(key));
  }

  
}

// app 本地存储
export const appLocalStorage = new LocalStorageManager('app');
